package com.example.waimai.util;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.Objects;
import java.util.UUID;

/**
 * OSS工具类 - 阿里云OSS服务器工具类
 *
 */
@Component
public class OssUtil {

    /*
     * 从配置文件获取阿里云OSS的相关配置
     */
    /**
     * 阿里云OSS的地域节点
     */
    @Value("${uposs.aliyun.oss.endpoint}")
    private String endpoint;

    /**
     * 阿里云OSS的存储空间名称
     */
    @Value("${uposs.aliyun.oss.bucketName}")
    private String bucketName;

    /**
     * 阿里云OSS的访问秘钥ID
     */
    @Value("${uposs.aliyun.oss.accessKeyID}")
    private String accessKeyID;

    /**
     * 阿里云OSS的访问秘钥凭证
     */
    @Value("${uposs.aliyun.oss.accessKeySecret}")
    private String accessKeySecret;

    /**
     * 阿里云OSS的存储空间的上传文件的存储目录
     */
    @Value("${uposs.aliyun.oss.uploadSaveDir}")
    private String uploadSaveDir;

    /**
     * 上传文件
     *
     * @param file 上传的文件
     * @return 上传成功之后文件的URL路径
     * @throws IOException IO异常
     */
    public String uploadFile(MultipartFile file,String prefix) throws IOException {
        //上传图片到OSS
        String fileUrl = uploadImg2OSS(file,prefix);
        System.out.println("uploadFile 1 ");
        //获取上传图片到OSS之后的URL路径
        String str = getURL(fileUrl);
        System.out.println("uploadFile 2 ");
        return str.trim();
    }


    /**
     * 上传图片到OSS
     *
     * @param file 上传的文件
     * @return 上传文件的新的名称
     * @throws IOException IO异常
     */
    @SuppressWarnings("deprecation")
    private String uploadImg2OSS(MultipartFile file,String prefix) throws IOException {
        // 1.生成新的文件名称(以防止文件名称重复)
        String fileName = file.getOriginalFilename();
        String suffix = Objects.requireNonNull(fileName).substring(fileName.lastIndexOf(".")).toLowerCase();
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String lastName =prefix +"-"+ uuid + suffix;

        // 2.上传文件到OSS
        InputStream inputStream = file.getInputStream();
        System.out.println("uploadImage 1 ");
        // 2.1创建上传的Object的metadata
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentLength(inputStream.available());
        objectMetadata.setCacheControl("no-cache");
        objectMetadata.setHeader("Pragma", "no-cache");
        objectMetadata.setContentType(FileUtil.getContentType(lastName.substring(lastName.lastIndexOf("."))));
        objectMetadata.setContentDisposition("inline;filename=" + lastName);
        System.out.println("uploadImage 2 ");
        // 2.2上传文件
        OSSClient ossClient = new OSSClient(endpoint, accessKeyID, accessKeySecret);
        System.out.println("uploadImage 3 ");
        ossClient.putObject(bucketName, uploadSaveDir + lastName, inputStream, objectMetadata);
        System.out.println("uploadImage 4 ");
        inputStream.close();
        return lastName;
    }

    /**
     * 获得URL链接
     *
     * @param lastName 上传文件的新的名称
     * @return 文件上传成功之后文件的URL路径
     */
    @SuppressWarnings("deprecation")
    private String getURL(String lastName) {
        // 设置URL的过期时间为20年, 即: 20*365*24*60*60*1000L 毫秒
        Date expiration = new Date(new Date().getTime() + 20*365*24*60*60*1000L);
        // 生成URL
        OSSClient ossClient = new OSSClient(endpoint, accessKeyID, accessKeySecret);
        URL url = ossClient.generatePresignedUrl(bucketName, lastName, expiration);
        // 去除URL的参数
        String tmp = url.toString().split("\\?")[0];
        int index = tmp.lastIndexOf("/") + 1;
        return tmp.substring(0, index) + uploadSaveDir + tmp.substring(index);
    }



}
